// 引用数据
import {saveData,getData} from '@/api/courseCategory_ajax'

let vueData;

function init(_vueData){
  vueData = _vueData;
}
function addRootForm(){
  vueData.title = '添加课程类别';
  vueData.parentName = "主类目";
  vueData.dialogFormVisible = true;
  //清空数据
  vueData.form ={
          name:undefined,
          parentId:0,
          level:1
          }
}

function addForm(data){
  let treeData = vueData.treeData;
  vueData.parentName = data.name;
  vueData.dialogFormVisible = true;
  //清空数据
  vueData.form ={
          name:undefined,
          parentId:data.id,
          level:data.level + 1
          }
}

function editForm(data){
  vueData.title = '修改分类信息';
  vueData.dialogFormVisible = true;
  //还原数据
  if(data.parentId === 0){
    vueData.parentName = '主类目'
  }else{
    let treeData = vueData.treeData;
    searchParentName(treeData,data.parentId);
  }
  vueData.form = Object.assign({},vueData.form,data);
}

function searchParentName(one,parentId){
  for (let two of one) {
    if(two.id === parentId){
      vueData.parentName = two.name;
      return
    }
    if(two.hasOwnProperty('children')){
      searchParentName(two.children,parentId);
    }
  }
}

function saveForm(){
  //验证数据有效性
  let valid = true;
  if(valid){
    saveData(vueData.form).then((resp)=>{
      //关闭对话框
      vueData.dialogFormVisible = false
      //重新加载数据
      loadData()
    })
  }
}
//私有方法，用于加载数据
function loadData(){
  getData().then(resp =>{
    if(resp.code == 1){
      vueData.treeData = resp.data
    }
  })
}

//打包，变为一个模块(类)
export default {
  init,
  loadData,
  addForm,
  addRootForm,
  editForm,
  saveForm
}
